package com.zxc.questionservice.service.impl;


import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zxc.common.ErrorCode;
import com.zxc.common.exception.BusinessException;
import com.zxc.oj.model.dto.questionsubmit.QuestionSubmitAddRequest;
import com.zxc.oj.model.dto.questionsubmit.QuestionSubmitQueryRequest;
import com.zxc.oj.model.entity.Question;
import com.zxc.oj.model.entity.QuestionSubmit;
import com.zxc.oj.model.entity.User;
import com.zxc.oj.model.enums.QuestionSubmitLanguageEnum;
import com.zxc.oj.model.enums.QuestionSubmitStatusEnum;
import com.zxc.oj.model.enums.UserRoleEnum;
import com.zxc.oj.model.vo.QuestionSubmitVO;
import com.zxc.questionservice.mapper.QuestionSubmitMapper;

import com.zxc.questionservice.message.MessageProducer;
import com.zxc.questionservice.service.QuestionService;
import com.zxc.questionservice.service.QuestionSubmitService;
import com.zxc.service.JudgeFeignClient;
import com.zxc.service.UserFeignClient;
import lombok.RequiredArgsConstructor;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.stream.Collectors;

/**
 * <p>
 * 题目提交 服务实现类
 * </p>
 *
 * @author author
 * @since 2024-02-10
 */
@RequiredArgsConstructor
@Service
public class QuestionSubmitServiceImpl extends ServiceImpl<QuestionSubmitMapper, QuestionSubmit> implements QuestionSubmitService {

    private final QuestionService questionService;



    private final JudgeFeignClient judgeFeignClient;

    private final MessageProducer messageProducer;
    /**
     * 问题提交
     *
     * @param questionSubmitAddRequest
     * @param loginUser
     * @return
     */
    @Override
    public long doQuestionSubmit(QuestionSubmitAddRequest questionSubmitAddRequest, User loginUser) {
        //校验语言是否合法
        QuestionSubmitLanguageEnum languageEnum = questionSubmitAddRequest.getLanguage();
        if (languageEnum == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "语言参数错误");
        }
        // 判断实体是否存在，根据类别获取实体
        Long questionId = questionSubmitAddRequest.getQuestionId();
        System.out.println(questionId);
        Question question = questionService.getById(questionId);
        if (question == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR);
        }
        // 是否已提交题目
        long userId = loginUser.getId();
        // 每个用户串行提交题目
        QuestionSubmit questionSubmit = new QuestionSubmit();
        questionSubmit.setUserId(userId);
        questionSubmit.setQuestionId(questionId);
        questionSubmit.setCode(questionSubmitAddRequest.getCode());
        questionSubmit.setLanguage(languageEnum);
        //设置初始化
        questionSubmit.setStatus(QuestionSubmitStatusEnum.WAITING.getValue());
        questionSubmit.setJudgeInfo(null);
        boolean save = save(questionSubmit);
        if (!save) {
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "题目提交失败");
        }
        Long questionSubmitId = questionSubmit.getId();
        //判题服务
        messageProducer.sendMessage("code_exchange","routingKey",String.valueOf(questionSubmitId));
        // 返回提交题目的id，方便后续查询该题目的提交情况
        return questionSubmitId;
    }


    /**
     * 获取查询包装类
     *
     * @param questionSubmitQueryRequest
     * @return
     */
    @Override
    public QueryWrapper<QuestionSubmit> getQueryWrapper(QuestionSubmitQueryRequest questionSubmitQueryRequest) {
        QueryWrapper<QuestionSubmit> queryWrapper = new QueryWrapper<>();
        if (questionSubmitQueryRequest == null) {
            return queryWrapper;
        }


        String language = questionSubmitQueryRequest.getLanguage();
        Integer status = questionSubmitQueryRequest.getStatus();
        Long questionId = questionSubmitQueryRequest.getQuestionId();
        Long userId = questionSubmitQueryRequest.getUserId();

        // 拼接查询条件
        queryWrapper.eq(ObjectUtils.isNotEmpty(language) && !language.isEmpty(), "language", language);
        queryWrapper.eq(ObjectUtils.isNotEmpty(status) && status != 0, "status", status);
        queryWrapper.eq(ObjectUtils.isNotEmpty(questionId) && questionId != 0, "questionId", questionId);
        queryWrapper.eq(ObjectUtils.isNotEmpty(userId) && userId != 0, "userId", userId);
        //根据创建时间升序
        queryWrapper.orderBy(true, true,
                "createTime");


        return queryWrapper;
    }

    @Override
    public QuestionSubmitVO getQuestionVO(QuestionSubmit questionSubmit, User loginUser) {
        QuestionSubmitVO questionSubmitVO = QuestionSubmitVO.objToVo(questionSubmit);

        // 仅本人或管理员可以看见提交的代码

        Long userId = loginUser.getId();

        if (!userId.equals(questionSubmit.getUserId()) && !UserRoleEnum.ADMIN.equals(loginUser.getUserRole())) {
            questionSubmitVO.setCode(null);
        }
        return questionSubmitVO;
    }

    @Override
    public Page<QuestionSubmitVO> getQuestionVOPage(Page<QuestionSubmit> questionSubmitPage, User loginUser) {
        List<QuestionSubmit> questionList = questionSubmitPage.getRecords();
        Page<QuestionSubmitVO> questionVOPage = new Page<>(questionSubmitPage.getCurrent(), questionSubmitPage.getSize(), questionSubmitPage.getTotal());
        if (CollUtil.isEmpty(questionList)) {
            return questionVOPage;
        }
        //封装VO对象，并设置语言名称，状态名称，用户名称，题目名称
        List<QuestionSubmitVO> collect = questionList.stream().map(questionSubmit -> getQuestionVO(questionSubmit, loginUser)).collect(Collectors.toList());

        questionVOPage.setRecords(collect);
        return questionVOPage;
    }
}
